﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using eShop.Model;
using eShop.DataAccess.Converter;
using eShop.DataAccess;

namespace eShop.Business
{
    public class OrderManager
    {
        public static bool CreateOrder(Order order)
        {
            DataAccess.Entity.Order eOrder = OrderConverter.ConvertToEntity(order);
            if (OrderDAL.Insert(eOrder))
            {
                order.OrderId = eOrder.Id;
                order.OrderItems.SetOrderId(order.OrderId);
                foreach(OrderItem orderItem in order.OrderItems)
                {
                    DataAccess.Entity.OrderItem eOrderItem = OrderItemConverter.ConvertToEntity(orderItem);
                    if (OrderItemDAL.Insert(eOrderItem))
                    {
                        orderItem.Id = eOrderItem.Id;
                    }
                }
                return true;
            }
            return false;
        }

        public static bool UpdateOrder(Order order)
        {
            return OrderDAL.Update(OrderConverter.ConvertToEntity(order));
        }

        public static bool DeleteOrderById(int orderId)
        {
            return OrderDAL.DeleteByKeys(orderId, null);
        }

        public static Order GetOrderById(int orderId)
        {
            List<Order> orders = OrderConverter.ConvertToModelObject(OrderDAL.GetByKeys(orderId, null));
            if (orders.Count == 1)
            {
                orders[0].OrderItems = OrderItemConverter.ConvertToModelObject(OrderItemDAL.GetByKeys(null, orderId));
                return orders[0];
            }
            return null;
        }

        public static Order GetOrderByOrderNumber(string orderNumber)
        {
            return new Order();
        }

        public static List<Order> GetOrderByUser(int userId)
        {
            return new List<Order>();
        }

        public static List<Order> GetOrderByUserPaged(int userId, string orderBy, bool isAscending, int pageIndex, int pageSize, out int totalItems)
        {
            totalItems = 0;
            return new List<Order>();
        }

        public static List<Order> GetOrdersPaged(string orderStatus,string orderBy, bool isAscending, int pageIndex, int pageSize,int orderNo, DateTime? fromDate, DateTime? toDate)
        {
            List<Order> orders = OrderConverter.ConvertToModelObject(OrderDAL.GetOrdersPaged(orderStatus,orderBy, isAscending, pageIndex, pageSize, orderNo, fromDate, toDate));
            return orders;
        }

        public static Int32 GetOrdersPagedCount(string orderStatus,int orderNo, DateTime? fromDate, DateTime? toDate)
        {
            return OrderDAL.GetOrdersPagedCount(orderStatus, orderNo, fromDate, toDate);
            
        }
    }
}
